import path from 'path';
import fs from 'fs';

import ts from 'rollup-plugin-typescript2';
import cjs from '@rollup/plugin-commonjs';
import replace from '@rollup/plugin-replace';

// 指向packages文件夹路径
const pkgPath = path.resolve(__dirname, '../../packages');
// 打包产物路径
const distPath = path.resolve(__dirname, '../../dist/node_modules');

/** 根据包名，解析包路径 */
export function resolvePkgPath(pkgName, isDist = false) {
  if (isDist) {
    // 打包后的包路径
    return `${distPath}/${pkgName}`;
  }

  // 未经过打包的包路径
  return `${pkgPath}/${pkgName}`;
}

/** 获取包的package.json文件内容 */
export function getPackageJSON(pkgName) {
  // 找包的package.json路径
  const path = `${resolvePkgPath(pkgName)}/package.json`;

  const str = fs.readFileSync(path, {encoding: 'utf-8'});

  return JSON.parse(str);
}

//! 参数的含义是：如果没有传配置，则默认参数为一个空对象。然后再对这个参数对象进行解构，解构typescript属性。如果typescript属性为空，则赋值为空对象
export function getBaseRollupPlugins({alias = {__DEV__: true, preventAssignment: true}, typescript = {}} = {}) {
  return [replace(alias), cjs(), ts(typescript)];
}
